package com.xfapp.demos.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.security.Security;

public class WechatDecryptUtil {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 解密微信用户数据
     * @param encryptedData 前端传来的 encryptedData
     * @param iv 前端传来的 iv
     * @param sessionKey 微信返回的 session_key
     * @return 解密后的 JSON 字符串
     */
    public static String decrypt(String encryptedData, String iv, String sessionKey) throws Exception {
        byte[] keyBytes = Base64.decodeBase64(sessionKey);
        byte[] ivBytes = Base64.decodeBase64(iv);
        byte[] dataBytes = Base64.decodeBase64(encryptedData);

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, "AES"), new IvParameterSpec(ivBytes));
        byte[] result = cipher.doFinal(dataBytes);
        return new String(result, "UTF-8");
    }
}
